const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const koaBody = require('koa-body');

const index = require('./routes/index');
const koaSwagger = require('koa2-swagger-ui');
const logger = require('koa-logger')


const cors = require('./libs/cors')

const swagger = require('./libs/swagger');

// error handler
onerror(app)
    // middlewares

// koabody文档: http://www.ptbird.cn/koa-body.html
app.use(koaBody({
    multipart: true, // 支持文件上传
    urlencoded: true,
    text: true,
    json: true,
    encoding: 'utf-8',
    strict: false,
}));
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
    extension: 'pug'
}))

// 接口访问过滤器
app.use(cors);

// routes

app.use(index.routes(), index.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
});

// swagger配置
app.use( //注意这里需要看koa2-swagger-ui的版本 不然会报koaSwagger不是一个函数等错误
    koaSwagger({
        routePrefix: '/swagger', // host at /swagger instead of default /docs
        swaggerOptions: {
            url: '/swagger.json' // example path to json
        }
    })
);

module.exports = app